﻿using Abp.Application.Services;
using Abp.Domain.Repositories;
using Aspose.Cells;
using Microsoft.AspNetCore.Http;
using Polly.Caching;
using SportsPlatform.Base;
using SportsPlatform.Consts;
using SportsPlatform.Dto.SportBusiness.Employee;
using SportsPlatform.Dto.SportBusiness.Team;
using SportsPlatform.Dto.WeChat.Me;
using SportsPlatform.Helpers;
using SportsPlatform.Model.SportBusiness;
using SportsPlatform.Query.SportBusiness.Feedback;
using SportsPlatform.Query.WeChat;
using SportsPlatform.WeChat.IWeChat;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static NPOI.HSSF.Util.HSSFColor;

namespace SportsPlatform.WeChat.WeChat
{
    /// <summary>
    /// 我的服务接口实现
    /// </summary>
    [RemoteService(false)]
    public class MeService : SportsPlatformAppServiceBase, IMeService
    {
        private readonly IRepository<Employee, Guid> _repository;
        private readonly IRepository<Team, Guid> _teamRepository;
        private readonly IRepository<TeamUser, Guid> _teamUserRepository;
        private readonly IRepository<Feedback, Guid> _feedbacckRepository;
        private readonly IRepository<RegistrationInfo, Guid> _registrationInfoRepository;
        private readonly IRepository<Competition, Guid> _competitionRepository;
        public MeService(IRepository<Employee, Guid> repository, IRepository<Team, Guid> teamRepository,
            IRepository<TeamUser, Guid> teamUserRepository, IRepository<Feedback, Guid> feedbacckRepository,
            IRepository<RegistrationInfo, Guid> registerReoisitory, IRepository<Competition, Guid> competitionRepository
            , IHttpContextAccessor context) : base(context)
        {
            _repository = repository;
            _teamRepository = teamRepository;
            _teamUserRepository = teamUserRepository;
            _feedbacckRepository = feedbacckRepository;
            _registrationInfoRepository = registerReoisitory;
            _competitionRepository = competitionRepository;
        }

        /// <summary>
        /// 通过标识获取用户信息
        /// </summary>
        /// <param name="query">标识</param>
        /// <returns></returns>
        public async Task<ResultDto<WeCahtMeEmployeeDto>> GetByIdToEmployee(GetEmployeeByIdQuery query)
        {
            ResultDto<WeCahtMeEmployeeDto> resultDto = new ResultDto<WeCahtMeEmployeeDto>();
            try
            {
                var type = await _repository.SingleAsync(p => p.Id == query.Id);


                if (type != null)
                {
                    var dto = new WeCahtMeEmployeeDto
                    {
                        NickName = type.NickName,
                        HeadPortrait = type.HeadPortrait,
                        Id = type.Id,
                        IDNumber = type.IDNumber,
                        Phone = type.Phone,
                        RealName = type.RealName,
                        RegisterTime = type.RegisterTime.ToString("yyyy-MM-dd"),
                        Sensor = type.Sensor,
                        Sex = type.Sex,
                        Teams = new List<TeamListDto>()
                    };

                    var teamUsers = await _teamUserRepository.GetAllListAsync(tu => tu.EmployeeId == type.Id);

                    if (teamUsers.Count > 0)
                    {

                        foreach (var item in teamUsers)
                        {
                            var teams = await _teamRepository.GetAllListAsync(t => t.Id == item.TeamId);
                            if (teams.Count > 0)
                            {
                                foreach (var team in teams)
                                {
                                    dto.Teams.Add(new TeamListDto
                                    {
                                        Id = team.Id,
                                        TeamName = team.TeamName
                                    });
                                }
                            }
                        }

                    }
                    resultDto.Data = dto;
                }
                resultDto.Code = type != null ? HttpResultCode.Success : HttpResultCode.SqlError;
                resultDto.IsSuccess = type != null ? true : false;
                resultDto.Message = type != null ? "获取成功" : "获取失败";

            }
            catch (Exception e)
            {
                resultDto.Code = HttpResultCode.Error;
                resultDto.IsSuccess = false;
                resultDto.Message = e.Message;
            }
            return resultDto;
        }

        /// <summary>
        /// 更新用户信息
        /// </summary>
        /// <param name="query">传入参数</param>
        /// <returns></returns>
        public async Task<ResultDto<EmployeeDto>> UpdateEmployee(UpdateEmployeeQuery query)
        {
            ResultDto<EmployeeDto> resultDto = new ResultDto<EmployeeDto>();
            try
            {
                var user = await _repository.GetAsync(query.Id);

                if (user.IsNullAndEmpty())
                {
                    resultDto.Code = HttpResultCode.NotData;
                    resultDto.IsSuccess = false;
                    resultDto.Message = "当前用户不存在";
                    return resultDto;
                }

                if (!query.Sensor.IsNullAndEmpty())
                {
                    user.Sensor = query.Sensor;
                }
                if (!query.Phone.IsNullAndEmpty())
                {
                    user.Phone = query.Phone;
                }
                if (!query.HeadPortrait.IsNullAndEmpty())
                {
                    user.HeadPortrait = query.HeadPortrait;
                }
                if (!query.RealName.IsNullAndEmpty())
                {
                    user.RealName = query.RealName;
                }
                if (!query.Sex.IsNullAndEmpty())
                {
                    user.Sex = query.Sex;
                }
                if (!query.NickName.IsNullAndEmpty())
                {
                    user.NickName = query.NickName;
                }
                if (!query.IDNumber.IsNullAndEmpty())
                {
                    user.IDNumber = query.IDNumber;
                }
                var updateinformation = await _repository.UpdateAsync(user);

                resultDto.Code = !updateinformation.IsNullAndEmpty() ? HttpResultCode.Success : HttpResultCode.SqlError;
                resultDto.IsSuccess = !updateinformation.IsNullAndEmpty();
                resultDto.Message = !updateinformation.IsNullAndEmpty() ? "更新成功" : "更新失败";
                resultDto.Data = !updateinformation.IsNullAndEmpty() ? new EmployeeDto
                {
                    IDNumber = updateinformation.IDNumber,
                    HeadPortrait = updateinformation.HeadPortrait,
                    Id = updateinformation.Id,
                    NickName = updateinformation.NickName,
                    OpenId = updateinformation.OpenId,
                    Phone = updateinformation.Phone,
                    RealName = updateinformation.RealName,
                    Sensor = updateinformation.Sensor,
                    Sex = updateinformation.Sex,
                } : null;
            }
            catch (Exception e)
            {
                resultDto.Code = HttpResultCode.Error;
                resultDto.IsSuccess = false;
                resultDto.Message = e.Message;
            }
            return resultDto;
        }

        /// <summary>
        /// 获取团队列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<ResultListDto<WeChatTeamDto>> GetTeams(GetMeTeamEmployeeQuery query)
        {
            ResultListDto<WeChatTeamDto> resultDto = new ResultListDto<WeChatTeamDto>();
            var dto = new List<WeChatTeamDto>();
            try
            {
                //获取用户标识所对应的团队列表
                var userTeams = await _teamUserRepository.GetAllListAsync(tu => tu.EmployeeId == query.EmployeeId && tu.IsDeleted == false);

                if (userTeams.Count > 0)
                {
                    foreach (var item in userTeams)
                    {
                        WeChatTeamDto weChatGetMeTeamDto = new WeChatTeamDto();
                        var team = await _teamRepository.GetAsync(item.TeamId);
                        if (team != null)
                        {
                            weChatGetMeTeamDto.Id = team.Id;
                            weChatGetMeTeamDto.TeamName = team.TeamName;
                            weChatGetMeTeamDto.TeamNum = team.TeamNum;
                        }

                        var users = new List<WeChatEmployeeDto>();
                        //获取团队标识所对应的用户
                        var teamUsers = await _teamUserRepository.GetAllListAsync(tu => tu.TeamId == item.TeamId && tu.IsDeleted == false);
                        if (teamUsers.Count > 0)
                        {
                            foreach (var u in teamUsers)
                            {
                                var employee = await _repository.SingleAsync(e => e.Id == u.EmployeeId);
                                if (employee != null)
                                {
                                    users.Add(new WeChatEmployeeDto()
                                    {
                                        Id = employee.Id,
                                        Name = employee.RealName,
                                        IDNumber = employee.IDNumber,
                                        Sensor = employee.Sensor,
                                        Phone = employee.Phone,
                                    });
                                }
                            }
                        }

                        weChatGetMeTeamDto.Employees = users;
                        dto.Add(weChatGetMeTeamDto);
                    }

                    resultDto.Code = HttpResultCode.Success;
                    resultDto.IsSuccess = true;
                    resultDto.Message = "获取成功";
                    resultDto.Data = dto;
                }
                else
                {
                    resultDto.Code = HttpResultCode.NotData;
                    resultDto.IsSuccess = false;
                    resultDto.Message = "未获取到数据";
                }


            }
            catch (Exception e)
            {
                resultDto.Code = HttpResultCode.Error;
                resultDto.IsSuccess = false;
                resultDto.Message = e.Message;
            }
            return resultDto;
        }

        /// <summary>
        /// 开始添加意见反馈
        /// </summary>
        /// <param name="addFeedbackQuery">传入参数</param>
        /// <returns></returns>
        public async Task<BaseResultDto> AddFeedbackStart(AddFeedbackQuery addFeedbackQuery)
        {
            BaseResultDto resultDto = new BaseResultDto();
            try
            {
                var res = ObjectMapper.Map<Feedback>(addFeedbackQuery);

                var user = await _repository.GetAsync(addFeedbackQuery.EmployeeId);
                if (user.IsNullAndEmpty())
                {
                    resultDto.Code = HttpResultCode.Fail;
                    resultDto.IsSuccess = false;
                    resultDto.Message = "当前用户不存在";
                    return resultDto;
                }

                res.CreateTime = DateTime.Now;
                res.CreateUserId = user.Id;
                res.UserId = user.Id;
                res.CommitTime = DateTime.Now;
                res.Source = 1;

                var feedback = await _feedbacckRepository.InsertAsync(res);

                resultDto.Code = !feedback.IsNullAndEmpty() ? HttpResultCode.Success : HttpResultCode.SqlError;
                resultDto.IsSuccess = !feedback.IsNullAndEmpty();
                resultDto.Message = !feedback.IsNullAndEmpty() ? "添加成功" : "添加失败";
            }
            catch (Exception e)
            {
                resultDto.Code = HttpResultCode.Error;
                resultDto.IsSuccess = false;
                resultDto.Message = e.Message;
            }
            return resultDto;
        }

        /// <summary>
        /// 获取用户报名总数
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<ResultDto<int>> GetRegisterCount(GetEmployeeRegisterQuery query)
        {
            ResultDto<int> resultDto = new ResultDto<int>();
            try
            {
                var employee = await _repository.GetAsync(query.EmployeeId);
                if (employee.IsNullAndEmpty())
                {
                    return new ResultDto<int>
                    {
                        Code = HttpResultCode.NotData,
                        Data = 0,
                        IsSuccess = false,
                        Message = "当前用户不存在"
                    };
                }

                var register = await _registrationInfoRepository.GetAllListAsync(r => r.EmployeeId == employee.Id && r.IsDeleted == false);
                if (register.Count > 0)
                {
                    return new ResultDto<int>
                    {
                        Code = HttpResultCode.Success,
                        Data = register.Count,
                        IsSuccess = true,
                        Message = "查询成功"
                    };
                }
                else
                {
                    return new ResultDto<int>
                    {
                        Code = HttpResultCode.Success,
                        Data = 0,
                        IsSuccess = true,
                        Message = "未查询到数据"
                    };
                }
            }
            catch (Exception e)
            {
                resultDto.Code = HttpResultCode.Error;
                resultDto.IsSuccess = false;
                resultDto.Message = e.Message;
            }
            return resultDto;
        }

        /// <summary>
        /// 获取赛事总条数
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<ResultDto<int>> GetCompetitionCount(GetEmployeeRegisterQuery query)
        {
            ResultDto<int> resultDto = new ResultDto<int>();
            try
            {
                var employee = await _repository.GetAsync(query.EmployeeId);
                if (employee.IsNullAndEmpty())
                {
                    return new ResultDto<int>
                    {
                        Code = HttpResultCode.NotData,
                        Data = 0,
                        IsSuccess = false,
                        Message = "当前用户不存在"
                    };
                }
                var registers = await _registrationInfoRepository.GetAllListAsync(r => r.EmployeeId == employee.Id && r.IsDeleted == false);

                var competitions = await _competitionRepository.GetAllListAsync(r => r.IsDeleted == false && r.IsEnable == 1);
                List<Competition> competitionList = new List<Competition>();
                registers.ForEach(r =>
                {
                    var competition = competitions.FirstOrDefault(c => c.Id == r.CompetitionId);
                    competitionList.Add(competition);
                });
                if (competitionList.Count > 0)
                {
                    return new ResultDto<int>
                    {
                        Code = HttpResultCode.Success,
                        Data = competitionList.Count,
                        IsSuccess = true,
                        Message = "查询成功"
                    };
                }
                else
                {
                    return new ResultDto<int>
                    {
                        Code = HttpResultCode.Success,
                        Data = 0,
                        IsSuccess = true,
                        Message = "未查询到数据"
                    };
                }
            }
            catch (Exception e)
            {
                resultDto.Code = HttpResultCode.Error;
                resultDto.IsSuccess = false;
                resultDto.Message = e.Message;
            }
            return resultDto;
        }

        /// <summary>
        /// 通过用户id获取最新创建的团队名称
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public async Task<ResultDto<string>> GetByEmloyeeId(GetEmployeeRegisterQuery query)
        {
            ResultDto<string> resultDto = new ResultDto<string>();
            try
            {
                var res = await _teamUserRepository.GetAllListAsync(te => te.EmployeeId == query.EmployeeId);
                var teams = await _teamRepository.GetAllListAsync();
                List<Team> teamsList = new List<Team>();
                if (res.Count > 0)
                {
                    res.ForEach(r =>
                    {
                        Team team = new Team();
                        team = teams.FirstOrDefault(t => t.Id == r.TeamId);
                        teamsList.Add(team);
                    });
                    var teamName = teamsList.OrderByDescending(t => t.CreateTime).FirstOrDefault().TeamName;
                    resultDto.Code = 200;
                    resultDto.IsSuccess = true;
                    resultDto.Message = "查询成功";
                    resultDto.Data = teamName;
                    return resultDto;
                }
                else
                {
                    resultDto.Code = HttpResultCode.NotData;
                    resultDto.IsSuccess = false;
                    resultDto.Message = "未查询到数据";
                    return resultDto;
                }
            }
            catch (Exception e)
            {
                resultDto.Code = HttpResultCode.Error;
                resultDto.IsSuccess = false;
                resultDto.Message = e.ToString();
                return resultDto;
                throw;
            }
        }
    }
}